﻿#include "ssDump.h"
#ifdef _WIN32
#include <windows.h>
#include "Dbghelp.h"
#else
#include <sys/resource.h>
#include "../ssShell.h"
#endif
#include <cstdio>


namespace StarSeeker
{

#ifdef _WIN32
long __stdcall MyUnhandledExceptionFilter( _EXCEPTION_POINTERS* ExceptionInfo )
{
	HANDLE lhDumpFile = CreateFileA("DumpFile.dmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL ,NULL);

	MINIDUMP_EXCEPTION_INFORMATION loExceptionInfo;
	loExceptionInfo.ExceptionPointers = ExceptionInfo;
	loExceptionInfo.ThreadId = GetCurrentThreadId();
	loExceptionInfo.ClientPointers = TRUE;

	MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),lhDumpFile, MiniDumpNormal, &loExceptionInfo, NULL, NULL);

	CloseHandle(lhDumpFile);
	return EXCEPTION_EXECUTE_HANDLER;
}
#endif

void CreateDumpFile()
{
#ifdef _WIN32
	SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
	printf("coreFile is create \"DumpFile.dmp\"\n");
#else
	rlimit limit;
	rlimit rlim_new;
	if( getrlimit(RLIMIT_CORE,&limit)==0 )
	{
		rlim_new.rlim_cur = rlim_new.rlim_max = 10737418240l;//10G，RLIM_INFINITY:无限
		if (setrlimit(RLIMIT_CORE, &rlim_new)!=0)
		{
			rlim_new.rlim_cur = rlim_new.rlim_max = limit.rlim_max;
			if( setrlimit(RLIMIT_CORE, &rlim_new) == 0 )
			{
				printf("coreFile is open, h = %ld  : c = %ld\r\n", rlim_new.rlim_max, rlim_new.rlim_cur);
				return;
			}
			else
			{
				printf("coreFile set failed, h = %ld  : c = %ld\r\n", rlim_new.rlim_max, rlim_new.rlim_cur);
			}
		}
		else
		{
			printf("coreFile is open, h = %ld  : c = %ld\r\n", rlim_new.rlim_max, rlim_new.rlim_cur);
			return;
		}
	}
	ShellCommand("ulimit -c unlimited");
#endif
}

}
//	struct sigaction act;
//	sigemptyset(&act.sa_mask);
//	act.sa_flags = SA_SIGINFO;
//	act.sa_sigaction = procGDBErr;
//	sigaction(SIGINT,&act,NULL);
//	sigaction(SIGTRAP,&act,NULL);
//	sigaction(SIGTERM,&act,NULL);
//
//void procGDBErr(int, siginfo_t *, void *)
//{
//	char temp[256];
//	memset(temp ,0 ,256);
//	sprintf(temp,"kill -9  %d \n", getpid());
//	system(temp);
//	printf("kill over\r\n");
//}
